STA接收UDP訊息並回傳OK的程式碼
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#define WIFI_SSID "ESP8266"
#define WIFI_PASS "password"
#define UDP_PORT 1026
WiFiUDP UDP;
char packet[255];
char reply[] = "OK";
void setup() {
Serial.begin(9600);
WiFi.begin(WIFI_SSID, WIFI_PASS);
Serial.print("Connecting to ");
Serial.print(WiFi.SSID());
while (WiFi.status() != WL_CONNECTED){
delay(100);
Serial.print(".");
}
Serial.println();
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
UDP.begin(UDP_PORT);
}
void loop() {
if(int packetSize = UDP.parsePacket()){//有接收到訊息的時候packetSize就會大於0,使條件式成立
if (int len = UDP.read(packet, 255)){
packet[len] = '\0'; // 在訊息後面補上\0,讓arduino知道字串到哪裡結束
}
Serial.print("資料內容: ");
Serial.println(packet);
//回傳訊息
UDP.beginPacket(UDP.remoteIP(),UDP.remotePort());
UDP.write(reply);
UDP.endPacket();
}
}